package com.yx.changdao.web.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yx.changdao.common.annotation.AutoLog;
import com.yx.changdao.common.annotation.ShiroDesc;
import com.yx.changdao.common.data.Pager;
import com.yx.changdao.common.data.Result;
import com.yx.changdao.common.entity.Problem;
import com.yx.changdao.common.entity.ProblemDeal;
import com.yx.changdao.common.enums.ScoreEnum;
import com.yx.changdao.common.exception.AlertException;
import com.yx.changdao.common.utils.*;
import com.yx.changdao.common.vo.ProblemScoreVo;
import com.yx.changdao.common.vo.ProblemVo;
import com.yx.changdao.service.ProblemDealService;
import com.yx.changdao.service.ProblemService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 问题结果评分模块
 *
 * @Auther: zcz
 * @create 2020/05/09 16:51
 */
@RestController
@RequestMapping("/problem/score/modify")
public class ProblemScoreModifyController {

    /**
     * 问题服务
     */
    @Autowired
    private ProblemService problemService;

    /**
     * 处理结果
     */
    @Autowired
    private ProblemDealService problemDealService;

    /**
     * 已评价列表
     *
     * @return Result
     */
    @AutoLog
    @GetMapping("/list")
    @RequiresPermissions("problem:score:modify:list")
    @ShiroDesc("问题评价修改:列表")
    public Result listReport(@RequestParam(value = "page") Long page,
                             @RequestParam(value = "limit", required = false) Integer limit) throws AlertException {

        if (limit == null) {
            limit = SysConst.LIMIT_PAGE;
        }

        // 分页配置
        Page<Problem> pager = new Page<>(page, limit);
        // 根据请求解析条件。
        QueryWrapper<Problem> qw = SysUtils.autoCnd(Problem.class);
        qw.orderByDesc(Problem.CREATE_TIME); //时间倒序
        qw.eq(Problem.IF_ASSESS,1);
        IPage<Problem> voIPage = problemService.page(pager, qw);

        IPage<ProblemScoreVo> problemScoreVoPage = new Page<>();
        List<ProblemScoreVo> reu = new ArrayList<>();
        voIPage.getRecords().forEach(v -> {
            ProblemScoreVo problemScoreVo = new ProblemScoreVo();
            BeanUtils.copyProperties(v, problemScoreVo);
            problemScoreVo.setAssessResultName(assessResultToName(problemScoreVo.getAssessResult()));
            problemScoreVo.setResidentIdcard(DesensitizationUtils.idEncrypt(problemScoreVo.getResidentIdcard()));
            reu.add(problemScoreVo);
        });
        problemScoreVoPage.setRecords(reu);
        problemScoreVoPage.setCurrent(voIPage.getCurrent());
        problemScoreVoPage.setTotal(voIPage.getTotal());
        problemScoreVoPage.setPages(voIPage.getPages());
        problemScoreVoPage.setSize(voIPage.getSize());
        Map<String, Object> map = new HashMap<>();
        map.put("list", problemScoreVoPage.getRecords());
        map.put("pager", new Pager(problemScoreVoPage));
        return Result.ok().data(map);
    }

    /**
     * 评分转中文
     * @param assessResult
     * @return
     */
    private String assessResultToName(int assessResult){
        for (ScoreEnum scoreEnum : ScoreEnum.values()) {
            if(scoreEnum.status().equals(assessResult)){
                return scoreEnum.info();
            }
        }
        return null;
    }

    /**
     * 已评价列表下拉菜单
     *
     * @return Result
     */
    @AutoLog
    @GetMapping("/score/select")
    private Result getScores(){
        List<Map<String, String>> list = new ArrayList<>();
        for (ScoreEnum scoreEnum : ScoreEnum.values()) {

            if(scoreEnum.status().equals(0)){
                continue;
            }

            HashMap<String, String> map = new HashMap<>();
            map.put("assessResult",String.valueOf(scoreEnum.status()));
            map.put("assessResultName",scoreEnum.info());
            list.add(map);
        }
        return Result.ok().data(list);
    }

    /**
     * 根据问题查询评分详情
     * @param problemId
     * @return
     * @throws AlertException
     */
    @AutoLog
    @GetMapping
//    @RequiresPermissions("problem:score:modify:look")
//    @ShiroDesc("问题评价修改:查询")
    public Result getProblemScore(@RequestParam("problemId") Integer problemId) throws AlertException {
        Problem problem = problemService.getOne(new QueryWrapper<Problem>().eq(Problem.ID, problemId));
        Faster.throwNull(problem,"未查到问题信息");
        ProblemScoreVo problemScoreVo = new ProblemScoreVo();
        BeanUtils.copyProperties(problem, problemScoreVo);
        return Result.ok().data(problemScoreVo);
    }

    /**
     * 修改评分保存
     * @param problemId
     * @param assessResult
     * @return
     * @throws AlertException
     */
    @AutoLog
    @PutMapping
//    @RequiresPermissions("problem:score:modify:save")
//    @ShiroDesc("问题评价修改:保存")
    public Result update(@RequestParam("problemId") Integer problemId,
                         @RequestParam("assessResult") Integer assessResult) throws AlertException {
        if(!isContains(assessResult)){
            throw new AlertException("评分不正确,分数在1-3之间");
        }

        boolean b = problemService.update(new UpdateWrapper<Problem>()
                .set(Problem.ASSESS_RESULT, assessResult)
                .set(Problem.ASSESS_TIME,Faster.now())
                .eq(Problem.ID, problemId));

        if (!b) {
            throw new AlertException("评分修改失败");
        }
        return Result.ok("评分修改成功");
    }


    /**
     * 检查评分是否正确
     * @param assessResult
     * @return
     */
    public static boolean isContains(Integer assessResult) {
        for (ScoreEnum scoreEnum : ScoreEnum.values()) {
            if(scoreEnum.status().equals(assessResult)){
                return true;
            }
        }
        return false;
    }


    /**
     */
    @AutoLog
    @GetMapping("/export")
    public void export(@RequestParam("ids") String ids) throws Exception {

        QueryWrapper<Problem> qw = SysUtils.autoCnd(Problem.class);
        qw.eq(Problem.IF_ASSESS,1); //已评价

        List<Integer> idls = Faster.batch2(ids);

        if (!idls.isEmpty()) {
            qw.in(Problem.ID, idls);
        }

        List<Problem> list = problemService.list(qw);

        List<ProblemVo> collect = list.stream().map(t -> {
            ProblemVo problemVo = new ProblemVo();
            BeanUtils.copyProperties(t, problemVo);
            ProblemDeal one = problemDealService.getOne(new QueryWrapper<ProblemDeal>() //最新处理结果
                    .select(ProblemDeal.DEAL_CONTENT)
                    .eq(ProblemDeal.PROBLEM_ID, t.getId())
                    .orderByDesc(ProblemDeal.CREATE_TIME).last("limit 0,1"));

            if (Faster.isNotNull(one)) {
                problemVo.setDealContent(one.getDealContent());
            } else {
                problemVo.setDealContent("");
            }
            problemVo.setAssessResultCon(ScoreEnum.result(problemVo.getAssessResult()));
            return problemVo;

        }).collect(Collectors.toList());


        List<String> cloudms = new ArrayList<>();
        cloudms.add("residentName:反馈居民姓名");
        cloudms.add("residentAddress:反馈居民地址");
        cloudms.add("residentIdcard:反馈居民身份证号");
        cloudms.add("category:意见建议类别");
        cloudms.add("industryCategory:意见建议行业类别");

        cloudms.add("contact1Name:联户人1姓名");
        cloudms.add("contact1Phone:联户人1手机号");
        cloudms.add("contact2Name:联户人2姓名");
        cloudms.add("contact2Phone: 联户人2手机号");

        cloudms.add("content:意见建议内容");
        cloudms.add("depName:承办部门");
        cloudms.add("difficultLevel:办理难度");
        cloudms.add("dealContent:最新处理结果");
        cloudms.add("assessResultCon:评价结果");

        ExcelImportExportUtils.writeExcelByCloum(collect, SysUtils.getResponse(), "导出", cloudms);
    }
}
